import math


def f(x):
    return x ** 3 - 2 * x + 1


def golden_section_search(a, b, epsilon):
    # 计算黄金比例相关的系数
    r = (3 - math.sqrt(5)) / 2
    c = a + r * (b - a)
    d = a + (1 - r) * (b - a)

    while (b - a) / 2 > epsilon:
        if f(c) < f(d):
            b = d
        else:
            a = c
            # 重新计算c和d
        c = a + r * (b - a)
        d = a + (1 - r) * (b - a)

        # 取中点作为近似解（或c和d中的任一个，因为它们此时非常接近）
    return (a + b) / 2


# 初始区间和精度
a, b = 0, 1
epsilon = 0.01

# 执行黄金分割法
min_x = golden_section_search(a, b, epsilon)
min_y = f(min_x)

print(f"Approximate minimum x ≈ {min_x:.4f}, Minimum f(x) ≈ {min_y:.4f}")
